package com.agileboot.medicine.customize.async;


import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.agileboot.common.enums.common.LoginStatusEnum;
import com.agileboot.common.utils.ServletHolderUtil;
import com.agileboot.common.utils.ip.IpRegionUtil;
import com.agileboot.domain.system.log.db.SysLoginInfoEntity;
import com.agileboot.domain.system.log.db.SysLoginInfoService;
import com.agileboot.domain.system.log.db.SysOperationLogEntity;
import com.agileboot.domain.system.log.db.SysOperationLogService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;

/**
 * 异步工厂
 *
 * @author lx
 */
@Slf4j
public class AsyncTaskFactory {
    private AsyncTaskFactory() {
    }

    public static Runnable loginInfoTask(final String username, final LoginStatusEnum loginStatusEnum, final String message) {
        //用户代理，检测是否是真人，减少爬虫攻击，通过ip锁定，判断在某个时间段访问的次数，超过了之后就禁止他一段时间
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletHolderUtil.getRequest().getHeader("User-Agent"));
        //获取客户端浏览器对象
        final Browser browser = userAgent.getBrowser();
        //获取浏览器的名字
        final String name = browser != null ? browser.getName() : "";
        //通过请求request获取用户ip
        final String ip = ServletUtil.getClientIP(ServletHolderUtil.getRequest());
        //通过ip和获取地址
        final String address = IpRegionUtil.getBriefLocationByIp(ip);
        //获取客户操作系统
        final String os = userAgent.getOperatingSystem() != null ? userAgent.getOperatingSystem().getName() : "";

        //打印日志
        log.info("ip:{},address:{},username:{},loginStatusEnum:{},message:{}",ip,address,username,loginStatusEnum,message);

        //创建一个线程任务
        return () -> {
            //封装用户登录信息，日志
            SysLoginInfoEntity loginInfo = new SysLoginInfoEntity();
            loginInfo.setUsername(username);
            loginInfo.setIpAddress(ip);
            loginInfo.setLoginLocation(address);
            loginInfo.setBrowser(name);
            loginInfo.setOperationSystem(os);
            loginInfo.setMsg(message);
            loginInfo.setLoginTime(DateUtil.date());
            loginInfo.setStatus(loginStatusEnum.getValue());
            // 插入数据
            SpringUtil.getBean(SysLoginInfoService.class).save(loginInfo);
        };
    }

    /**
     * 操作日志记录
     * operationLog 操作日志信息
     *return 任务task
     */
    public static Runnable recordOperationLog(final SysOperationLogEntity operationLog){
        return () ->{
            //远程查询操作地点
            operationLog.setOperatorLocation(IpRegionUtil.getBriefLocationByIp(operationLog.getOperatorIp()));
            SpringUtil.getBean(SysOperationLogService.class).save(operationLog);
        };
    }

}
